/**
 * 朋知云学平台Web端API接口
 * 提供与后端交互的接口，支持本地模拟数据
 */

// 模拟数据存储
const mockStorage = {
  users: [],
  demands: [],
  applications: [],
  collections: [],
  // 初始化本地存储
  init() {
    // 从localStorage获取数据，如果没有则初始化
    const storedUsers = localStorage.getItem('mock_users');
    const storedDemands = localStorage.getItem('mock_demands');
    const storedApplications = localStorage.getItem('mock_applications');
    const storedCollections = localStorage.getItem('mock_collections');
    
    this.users = storedUsers ? JSON.parse(storedUsers) : [];
    this.demands = storedDemands ? JSON.parse(storedDemands) : [];
    this.applications = storedApplications ? JSON.parse(storedApplications) : [];
    this.collections = storedCollections ? JSON.parse(storedCollections) : [];
    
    // 如果没有数据，创建一些初始数据
    if (this.users.length === 0) {
      this.users.push({
        id: 1,
        username: 'teacher1',
        password: '123456',
        phone: '13800138000',
        email: 'teacher1@example.com',
        userType: 'teacher',
        avatar: '/static/avatar1.png'
      });
      this.users.push({
        id: 2,
        username: 'school1',
        password: '123456',
        phone: '13900139000',
        email: 'school1@example.com',
        userType: 'school',
        avatar: '/static/avatar-default.png'
      });
      localStorage.setItem('mock_users', JSON.stringify(this.users));
    }
    
    if (this.demands.length === 0) {
      this.demands.push({
        id: 1,
        title: '山区小学英语教师支教需求',
        schoolName: '山区希望小学',
        location: '云南省丽江市宁蒗县',
        needCount: 2,
        duration: '3个月',
        content: '我们是一所山区小学，急需英语教师进行支教，提高学生的英语水平。',
        contact: '13800138001',
        status: '招募中',
        subject: '英语',
        images: ['/static/touxiang.jpeg'],
        createTime: '2023-05-15 10:00:00'
      });
      this.demands.push({
        id: 2,
        title: '乡村学校数学教师支教需求',
        schoolName: '阳光乡村学校',
        location: '四川省凉山彝族自治州',
        needCount: 1,
        duration: '6个月',
        content: '我校数学教师紧缺，希望有爱心人士前来支教。',
        contact: '13900139001',
        status: '招募中',
        subject: '数学',
        images: ['/static/touxiang.jpeg'],
        createTime: '2023-05-20 14:30:00'
      });
      localStorage.setItem('mock_demands', JSON.stringify(this.demands));
    }
    
    if (this.applications.length === 0) {
      this.applications.push({
        id: 1,
        userId: 1,
        demandId: 1,
        details: '我是一名有5年教学经验的英语教师，希望能够参与支教活动。',
        availableTime: '2023-07-01至2023-09-30',
        status: '待审核',
        teachingExperience: '5年英语教学经验，有支教经历',
        createTime: '2023-05-16 09:15:00'
      });
      localStorage.setItem('mock_applications', JSON.stringify(this.applications));
    }
    
    if (this.collections.length === 0) {
      this.collections.push({
        id: 1,
        userId: 1,
        demandId: 2,
        createTime: '2023-05-21 16:45:00'
      });
      localStorage.setItem('mock_collections', JSON.stringify(this.collections));
    }
  },
  // 保存数据到本地存储
  saveUsers() {
    localStorage.setItem('mock_users', JSON.stringify(this.users));
  },
  saveDemands() {
    localStorage.setItem('mock_demands', JSON.stringify(this.demands));
  },
  saveApplications() {
    localStorage.setItem('mock_applications', JSON.stringify(this.applications));
  },
  saveCollections() {
    localStorage.setItem('mock_collections', JSON.stringify(this.collections));
  }
};

// 初始化模拟数据
mockStorage.init();

// 通用响应格式
const createResponse = (data = null, code = 200, msg = null) => {
  return {
    code,
    msg,
    data
  };
};

// 判断是否使用模拟数据
const useMock = true; // 设置为true表示使用模拟数据，false表示使用真实接口

// 配置信息
const config = {
  baseUrl: 'https://jsonplaceholder.typicode.com' // 测试用接口
};

// 封装请求方法
const request = (url, method, data) => {
  if (useMock) {
    // 使用模拟数据
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockResponse = handleMockRequest(url, method, data);
        resolve(mockResponse);
      }, 300); // 模拟网络延迟
    });
  } else {
    // 使用真实接口
    return new Promise((resolve, reject) => {
      fetch(config.baseUrl + url, {
        method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: method !== 'GET' ? JSON.stringify(data) : undefined
      })
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error));
    });
  }
};

// 处理模拟请求
const handleMockRequest = (url, method, data) => {
  // 用户认证模块
  if (url === '/user/register' && method === 'POST') {
    return handleUserRegister(data);
  } else if (url === '/user/login' && method === 'POST') {
    return handleUserLogin(data);
  } else if (url.startsWith('/user/profile/') && method === 'GET') {
    const id = parseInt(url.split('/').pop());
    return handleGetUserProfile(id);
  }
  
  // 需求管理模块
  else if (url === '/demands' && method === 'POST') {
    return handleCreateDemand(data);
  } else if (url === '/demands' && method === 'GET') {
    return handleGetDemands(data);
  } else if (url.startsWith('/demands/') && method === 'GET' && !url.includes('collect')) {
    const id = parseInt(url.split('/').pop());
    return handleGetDemandDetail(id);
  } else if (url === '/demands/collect' && method === 'POST') {
    return handleCollectDemand(data);
  }
  
  // 申请管理模块
  else if (url === '/applications' && method === 'POST') {
    return handleCreateApplication(data);
  } else if (url === '/applications' && method === 'GET') {
    return handleGetApplications(data);
  } else if (url.startsWith('/applications/') && method === 'GET') {
    const id = parseInt(url.split('/').pop());
    return handleGetApplicationDetail(id);
  }
  
  // 未匹配到的接口
  return createResponse(null, 404, '接口不存在');
};

// 用户认证模块处理函数
const handleUserRegister = (data) => {
  const { username, password, phone, email, userType } = data;
  
  // 检查用户名是否已存在
  const existingUser = mockStorage.users.find(user => user.username === username);
  if (existingUser) {
    return createResponse(null, 400, '用户名已存在');
  }
  
  // 创建新用户
  const newUser = {
    id: mockStorage.users.length > 0 ? Math.max(...mockStorage.users.map(u => u.id)) + 1 : 1,
    username,
    password,
    phone,
    email,
    userType,
    avatar: '/static/avatar-default.png'
  };
  
  mockStorage.users.push(newUser);
  mockStorage.saveUsers();
  
  return createResponse({ id: newUser.id });
};

const handleUserLogin = (data) => {
  const { username, password } = data;
  
  // 查找用户
  const user = mockStorage.users.find(u => u.username === username && u.password === password);
  if (!user) {
    return createResponse(null, 401, '用户名或密码错误');
  }
  
  return createResponse({ id: user.id });
};

const handleGetUserProfile = (id) => {
  const user = mockStorage.users.find(u => u.id === id);
  if (!user) {
    return createResponse(null, 404, '用户不存在');
  }
  
  // 不返回密码字段
  const { password, ...userInfo } = user;
  return createResponse(userInfo);
};

// 需求管理模块处理函数
const handleCreateDemand = (data) => {
  const newDemand = {
    ...data,
    id: mockStorage.demands.length > 0 ? Math.max(...mockStorage.demands.map(d => d.id)) + 1 : 1,
    createTime: new Date().toLocaleString()
  };
  
  mockStorage.demands.push(newDemand);
  mockStorage.saveDemands();
  
  return createResponse({ id: newDemand.id });
};

const handleGetDemands = (params) => {
  const { page = 1, pageSize = 10, content = '', subject = '' } = params;
  
  // 筛选需求
  let filteredDemands = mockStorage.demands;
  if (content) {
    filteredDemands = filteredDemands.filter(d => 
      d.title.includes(content) || d.content.includes(content)
    );
  }
  if (subject) {
    filteredDemands = filteredDemands.filter(d => d.subject === subject);
  }
  
  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const pagedDemands = filteredDemands.slice(start, end);
  
  // 简化返回数据
  const list = pagedDemands.map(({ id, title, schoolName, location, needCount, duration, status, createTime }) => ({
    id, title, schoolName, location, needCount, duration, status, createTime
  }));
  
  return createResponse({
    total: filteredDemands.length,
    list
  });
};

const handleGetDemandDetail = (id) => {
  const demand = mockStorage.demands.find(d => d.id === id);
  if (!demand) {
    return createResponse(null, 404, '需求不存在');
  }
  
  return createResponse(demand);
};

const handleCollectDemand = (data) => {
  const { userId, demandId } = data;
  
  // 检查需求和用户是否存在
  const demand = mockStorage.demands.find(d => d.id === demandId);
  const user = mockStorage.users.find(u => u.id === userId);
  
  if (!demand || !user) {
    return createResponse(null, 404, '需求或用户不存在');
  }
  
  // 检查是否已收藏
  const existingCollection = mockStorage.collections.find(
    c => c.userId === userId && c.demandId === demandId
  );
  
  if (existingCollection) {
    // 取消收藏
    const index = mockStorage.collections.findIndex(c => c.id === existingCollection.id);
    mockStorage.collections.splice(index, 1);
  } else {
    // 添加收藏
    const newCollection = {
      id: mockStorage.collections.length > 0 ? Math.max(...mockStorage.collections.map(c => c.id)) + 1 : 1,
      userId,
      demandId,
      createTime: new Date().toLocaleString()
    };
    mockStorage.collections.push(newCollection);
  }
  
  mockStorage.saveCollections();
  return createResponse(null);
};

// 申请管理模块处理函数
const handleCreateApplication = (data) => {
  const newApplication = {
    ...data,
    id: mockStorage.applications.length > 0 ? Math.max(...mockStorage.applications.map(a => a.id)) + 1 : 1,
    createTime: new Date().toLocaleString()
  };
  
  mockStorage.applications.push(newApplication);
  mockStorage.saveApplications();
  
  return createResponse({ id: newApplication.id });
};

const handleGetApplications = (params) => {
  const { page = 1, pageSize = 10, details = '' } = params;
  
  // 筛选申请
  let filteredApplications = mockStorage.applications;
  if (details) {
    filteredApplications = filteredApplications.filter(a => 
      a.details.includes(details)
    );
  }
  
  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const pagedApplications = filteredApplications.slice(start, end);
  
  // 简化返回数据
  const list = pagedApplications.map(({ id, status, details, createTime }) => ({
    id, status, details, createTime
  }));
  
  return createResponse({
    total: filteredApplications.length,
    list
  });
};

const handleGetApplicationDetail = (id) => {
  const application = mockStorage.applications.find(a => a.id === id);
  if (!application) {
    return createResponse(null, 404, '申请不存在');
  }
  
  return createResponse(application);
};

// 导出API接口
const api = {
  // 用户认证模块
  userRegister: (data) => request('/user/register', 'POST', data),
  userLogin: (data) => request('/user/login', 'POST', data),
  getUserProfile: (id) => request(`/user/profile/${id}`, 'GET'),

  // 需求管理模块
  createDemand: (data) => request('/demands', 'POST', data),
  getDemands: (params) => request('/demands', 'GET', params),
  getDemandDetail: (id) => request(`/demands/${id}`, 'GET'),
  collectDemand: (data) => request('/demands/collect', 'POST', data),

  // 申请管理模块
  createApplication: (data) => request('/applications', 'POST', data),
  getApplications: (params) => request('/applications', 'GET', params),
  getApplicationDetail: (id) => request(`/applications/${id}`, 'GET')
};

// 导出API对象
export default api;